# -*- coding: utf-8 -*-
# @Time : 2022-06-01 14:34
# @Author : Z
# @Function :

from time import sleep
import cv2
import requests
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By


def FindPic(bg="../lib/verify/bg.png", block="../lib/verify/block.png"):
    """
    找出图像中最佳匹配位置
    :param bg: 目标即背景图
    :param block: 模板即需要找到的图
    :return: 返回最佳匹配及其最差匹配和对应的坐标
    """
    # 读取背景图片
    target_rgb = cv2.imread(bg)
    # 进行灰度处理
    target_gray = cv2.cvtColor(target_rgb, cv2.COLOR_BGR2GRAY)
    # 读取模板图片
    template_rgb = cv2.imread(block, 0)
    # 匹配缺口在背景图的位置
    res = cv2.matchTemplate(target_gray, template_rgb, cv2.TM_CCOEFF_NORMED)
    # 获取最差和最佳匹配
    value = cv2.minMaxLoc(res)
    print("获取最差和最佳匹配" + str(value))
    # 返回最佳匹配的x坐标
    return value[2][0]


# 在打开浏览器之前,去掉自动化标识
option = Options()
option.add_argument(r'--user-data-dir=C:\Users\15678\AppData\Local\Google\Chrome\User Data\Default')
option.add_experimental_option('excludeSwitches', ['enable-automation'])
option.add_argument('--disable-blink-features=AutomationControlled')
# 关掉密码弹窗
prefs = {}
prefs['credentials_enable_service'] = False
prefs['profile.password_manager_enabled'] = False
option.add_experimental_option('prefs', prefs)
driver = webdriver.Chrome(chrome_options=option)
driver.maximize_window()

# 输入账号和验证码
driver.implicitly_wait(10)
driver.get('https://www.zhihu.com/signin?next=%2F')
driver.maximize_window()
driver.find_element(By.XPATH, '//*[@name="username"]').send_keys('15678300490')
driver.find_element(By.XPATH, '//*[@name="digits"]').send_keys('123456')
# 点击获取验证码
# driver.find_element(By.XPATH, '//*[text()="获取短信验证码"]').click()

sleep(1)

while True:

    # 点击登陆
    driver.find_element(By.XPATH,'//*[text()="登录/注册"]').click()
    sleep(1)

    # 获取图片地址
    ele_bj = driver.find_element(By.XPATH, '//*[@class="yidun_bg-img"]')
    src_bj = ele_bj.get_attribute('src')
    ele_block = driver.find_element(By.XPATH, '//*[@class="yidun_jigsaw"]')
    src_block = ele_block.get_attribute('src')

    # 下载背景图片，并保存到本地
    img_bj = requests.get(src_bj).content
    f = open('../../lib/verify/bg.jpg', mode='wb')
    f.write(img_bj)
    f.close()

    # 下载滑块码，并保存到本地
    img_block = requests.get(src_block).content
    f = open('../../lib/verify/block.jpg', mode='wb')
    f.write(img_block)
    f.close()

    # 获取最佳偏移距离
    x = FindPic('../../lib/verify/bg.jpg', '../../lib/verify/block.jpg')
    print("没有缩放的x的值" + str(x))

    # 获取图片的渲染的宽度和下载后的宽度
    a = ele_bj.size.get("width")
    print("图片在网页的宽度" + str(a))
    b = ele_bj.get_attribute("naturalWidth")
    print("图片下载后的宽度" + str(a))
    # 计算缩放后的移动距离,selenium自带的不用乘屏幕设置的缩放比例
    x = int(x * int(a) / int(b)) + 10
    print("缩放后的x值" + str(x))

    # 按住滑块，移动计算后的距离
    action = ActionChains(driver)
    action.click_and_hold(ele_block).perform()
    action.move_by_offset(x, 0).perform()
    # 松开鼠标
    action.release().perform()
    sleep(1)

    try:
        # 只有移动失败的时候才弹出这个提示，要不会一直重试
        # //*[text()="10001:请求参数异常，请升级客户端后重试"]
        res = driver.find_element(By.XPATH, '//*[contains(text(),"系统繁忙")]').get_attribute("innerHTML")
        print(res)
        print()
    except:
        break

